;(function(Ext,metadata){
	Ext.Loader.setPath('FormFieldUtil',contextPath+"ui_tpl/FormFieldUtil.js");
	Ext.define("Ext.ux.TreeTab",{
		requires:[
			'Ext.tree.TreePanel',
			'Ext.tab.Panel',
			'Ext.data.TreeStore',
			'FormFieldUtil'
		],
		extend:'Ext.container.Container',
		xtype:'treetab',
		layout:'border',
		
		initComponent:function(){
			this.treeCmpId="tree"+metadata.id;
			this.tabPanelId="tabPanel"+metadata.id,
			this.attrs=metadata.attrs;
			this.fields=metadata.fields;
			this.buildNameFieldMap();
			this.refEnumMap=metadata.refEnumMap;
			this.refModelMap=metadata.refModelMap;
			this.requires=[];
			Ext.apply(this,this.attrs)
			this.initTreeConfig('west');
			this.initTabPanelConfig('center');
			this.items=[this.treeConfig,this.tabConfig];
			this.callParent();
		},
		
		buildNameFieldMap:function(){
			var me=this,nameFieldMap=this.nameFieldMap={},
			needKeyConvert=this.needKeyConvert=false,
			defaultValueMap=this.defaultValueMap={};
			Ext.iterate(this.fields,function(field,i){
				var name=field["name"];
				nameFieldMap[name]=field;
				if(Ext.isString(name)&&name.indexOf(".")>-1){
					needKeyConvert=true;
				}
				var defaultValue=field["attrs"]["defaultValue"];
				if(defaultValue){
					defaultValueMap[field["name"]]=defaultValue;
				}
			});
			this.fillDefaultValue();
		},
		
		fillDefaultValue:function(){
			var moduleIdField=this.nameFieldMap[this.moduleProperty];
			if(moduleIdField){
				var attrs=moduleIdField.attrs=moduleIdField.attrs||{};
				attrs["required"]=true;
				attrs["defaultValue"]=this.metaData["id"];
			}
		},
		
		
		initTreeTBar:function(){
			var me=this,
			
			tbar=[{
				text:"保存",
				iconCls:"fa fa-save",
				handler:function(){
					
				}
			},{
				text:"刷新",
				iconCls:"fa fa-refresh fa-fw",
				handler:function(){
					this.up('treepanel').store.reload();
				}
			}];
			return tbar;
			
		},
		
		refreshSelectedNode:function(){
			var me=this,tree=Ext.getCmp(me.treeCmpId),sels=tree.getSelection(),
			store=tree.store;
			if(sels.length==0){
				return store.reload();
			}
			var sel=sels[0],id=sel.get("id");
			me.refreshNode(id);
		},
		refreshNode:function(id){
			var me=this,tree=Ext.getCmp(me["treeCmpId"]),
	    	store=tree.store;
	    	var node = store.getNodeById(id),fid=node.raw.fid,
	    	fidNode=store.getNodeById(fid);
	    	store.load({node: fidNode, callback:function() {
	           var fidNode = store.getNodeById(fid);
	            tree.getSelectionModel().select(node, true, true);
	            fidNode.expand();
	        }, scope: this});
		},
		
		reloadNode:function(id){
			var me=this,tree=Ext.getCmp(me["treeCmpId"]),
	    	store=tree.store;
	    	var node = store.getNodeById(id);
	    	store.load({node: node, callback:function() {
	           var currentNode = store.getNodeById(node.raw.id);
	            tree.getSelectionModel().select(node, true, true);
	            node.expand();
	        }, scope: this});
		},
		
		buildTreeModel:function(){
			var me=this;
			return new Ext.data.TreeModel({
				 clientIdProperty: 'clientId',
				 identifier: 'negative',
				 idProperty:me.idProperty
			});
			
		},
		initTreeStore:function(){
			var me=this,action=me["action"],
			treeModel=this.buildTreeModel(),
			query=attrs["action"]||{type:"rest",url:""},
			queryUrl=query["url"];

			var proxy=this.buildProxy();
			
			var store= {
				autoDestroy :true,
				autoLoad :true,
				autoSync:true,
				proxy:proxy,
				defaultRootId:attrs["rootId"],
				defaultRootText:attrs["rootText"]||metadata["text"],
				parentIdProperty:me.parentIdProperty,
				model:treeModel,
				nodeParam:me.idProperty
			};
			return store;
		},
		buildProxy:function(){
			var attrs=this.attrs,
			action=attrs["action"],
			query=this.query=this.query||action,
			create=this.create=this.create||action,
			update=this.update=this.update||action,
			destroy=this.destroy=this.destroy||action,
			api={},actionMethods={},proxy={};
			if(action&&action.type=="rest"){
				proxy["type"]="rest";
				proxy["url"]=action["url"];
				proxy["appendId"]=true;
			}else{
				proxy["type"]="ajax";
				api["create"]=create.url;
				actionMethods["create"]=create.method||"POST";
				api["query"]=query.url;
				actionMethods["query"]=query.method||"GET";
				api["destroy"]=destroy.url;
				actionMethods["destroy"]=destroy.method||"GET";
				api["update"]=update["url"];
				actionMethods["update"]=update["method"]||"POST";
				proxy["url"]=query.url||action["url"];
				proxy["api"]=api;
				proxy["appendId"]=true;
				proxy["actionMethods"]=actionMethods;
			}
			proxy["reader"]={
				type:action["format"]||"json",
				rootProperty:'children',
				typeProperty:attrs["typeProperty"]
			};
			return proxy;
		},
		
		doDelete:function(){
			var me=this,tree=Ext.getCmp(me.treeCmpId),sels=tree.getSelection(),store=tree.store;
			
			if(sels.length==0)return Ext.toast('请先选择要删除的项目');
			var sel=sels[0],id=sel.get("id"),node=store.getNodeById(id);
			
			Ext.Msg.confirm('警告','确定要删除吗?',function(btn){
				if(btn=="no")return;
				node.erase();  
			});
		},
		showTab:function(id,metaId){
			var tabs=Ext.getCmp(me["tabCmpId"]),tabId="#"+metaId+id;
			var tab=tabs.child(tabId);
			if(!tab){
				var modelMeta=me["refMetaMap"][metaId],
				title=modelMeta["text"],modelAttr=modelMeta["attrs"],
				jsfile=modelAttr["jsfile"],cxtype=modelAttr["xtype"];
				Ext.require(jsfile);
				tab={
					title:title,
					xtype:cxtype,
					metaData:modelMeta,
					id:id,
					itemId:tabId
				};
				tabs.add(tab);
			}
			tabs.setActiveTab(tab);
		},
		initTreeConfig:function(region){
			var me=this,store=me.initTreeStore(),
			tbar=me.initTreeTBar(),
			listeners={'itemclick':function ( view, record, item, index, e, eOpts ) {
				var id=record.get(me["idProperty"]);
				
				
			}};
			var treeConfig=this.treeConfig={
					region:region,
					width:330,
					height:'auto',
					id:me.treeCmpId,
					store:store,
					xtype:"treepanel",
					split:true,
					tbar:tbar,
					rootVisible:false,
					listeners:listeners
			};
			if(me["seqProperty"]){
				treeConfig["viewConfig"]={
			        plugins: {
			            ptype: 'treeviewdragdrop',
			            containerScroll: true
			        }
			    };
				listeners["itemmove"]=function( node, oldParent, newParent, index, eOpts )  {
					var params={id:node.raw.id,fid:newParent.raw.id,seq:index};
					Ext.Ajax.request({
						url:me.moveSeqUrl,
						params:params,
						success:function(response, opts) {
							me.reloadNode(oldParent.raw.id);
							if(oldParent!=newParent){
								me.reloadNode(newParent.raw.id);
							}
							
					     },
						failure:function(response, opts){
							me.reloadNode(oldParent.raw.id);
							if(oldParent!=newParent){
								me.refreshSelectedNode();
							}
						}
					});
				}
			}
		},
		
		getEditorTab:function(traitId){
			var meta=refMetaMap[traitId],mattrs=meta["attrs"],
			tab={
					title:meta["text"],
					xtype:mattrs["xtype"]
			}
		},
		
		initTabPanelConfig:function(region){
			var me=this,config={
					id:me.tabPanelId,
			    xtype:"tabpanel",
				autoLoad:true,
			    region: region,
			    split:true,
			    items: []
			};
			this.tabConfig=config;
		},
		
		showAddNodeWin:function(){
			var me=this,moduleId=metadata["id"],attrs=me["attrs"],
			idProperty=attrs["idProperty"]||"id",
			typeProperty=attrs["typeProperty"]||"meta",
			winName=this.addNodeWinName="addNodeWin"+moduleId,
			action=attrs["action"];
			var win=Ext.getCmp(winName);
			if(!win){
				var items=FormFieldUtil.getFormFields(metaData);
				Ext.iterate(items,function(item,i){
					var name=item["name"];
					if(name=="rank"){
						item.value=(moduleId);
						item.hidden=true;
					}else if(name==idProperty){
						item.value=-1;
						item.hidden=true;
					}else if(name=="seq"){
						item.hidden=true;
					}else if(name=="flag"){
						item.value=1;
					}else if(name==me["parentIdProperty"]){
						item.readOnly=true;
					}
				});
				win=new Ext.form.Panel({
					floating:true,
					title:"新增",
					bodyPadding:10,
					url:action["url"],
					closeToolText:"关闭",
					draggable:true,
					modal:true,
					closable:true,
					scrollable:true,
					width:400,
					maxHeight:450,
					defaults:{
						xtype:"textfield",
						width:300
					},
					method:action["method"]||"PUT",
					items:items,
					buttons:[{
						text:'提交',
						formBind:true,
						handler:function(){
							 var win=this.up('form'),form = win.getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast("新增成功",'提示', 't');
					                    	me.refreshSelectedNode();
					                    	win.hide();
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.msg,'提示', 't');
					                    	me.refreshSelectedNode();
					                    }
					                });
					            }	
						}
					},{
						text:'取消',
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			var sels=Ext.getCmp(me.treeCmpId).getSelection();
			if(sels.length==0)return Ext.toast('请先选择父节点');
			var form=win.getForm(),pfield=form.findField(me.parentIdProperty);
			pfield&&pfield.setValue(sels[0].get(me.idProperty));
			Ext.iterate(this.defaultValueMap,function(name,v){
				var f=form.findField(name);
				f&&f.setValue(v);
			});
			win.show();
			
		},
		showEditNodeWin:function(){
			var me=this;
			var sels=Ext.getCmp(me.treeCmpId).getSelection();
			if(sels.length==0)return Ext.toast('请先选择父节点');
			var winName=this.editNodeWinName=this.editNodeWinName||("editNodeWin"+moduleId),
			update=me["update"],action=me["action"];
			var win=Ext.getCmp(winName);
			if(!win){
				var items=FormFieldUtil.getFormFields(metaData),
				moduleId=metaData["id"],
				idProperty=me["idProperty"],
				typeProperty=me["typeProperty"];
				Ext.iterate(items,function(item,i){
					var name=item["name"];
					if(name=="rank"){
						item.value=(moduleId);
						item.hidden=true;
					}else if(name=="seq"){
						item.hidden=true;
					}else if(name=="flag"){
						item.value=1;
					}
				});
				win=new Ext.form.Panel({
					floating:true,
					title:"编辑",
					bodyPadding:10,
					url:update["url"]||action["url"],
					closeToolText:"关闭",
					draggable:true,
					closable:true,
					modal:true,
					scrollable:true,
					width:400,
					maxHeight:450,
					defaults:{
						xtype:"textfield",
						width:300
					},
					method:update["method"]||"POST",
					items:items,
					buttons:[{
						text:'提交',
						formBind:true,
						handler:function(){
							 var win=this.up('form'),form = win.getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast("更新成功",'提示', 't');
					                    	me.refreshSelectedNode();
					                    	win.hide();
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.msg,'提示', 't');
					                    	me.refreshSelectedNode();
					                    }
					                });
					            }	
						}
					},{
						text:'取消',
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			var rec=sels[0],data=rec.data;
			if(this.needKeyConvert&&!data.flatten){
				data["flatten"]=true;
				Ext.apply(data,Ext.Object.flatten(data));
			}
			win.getForm().loadRecord(rec);
			win.show();
		},
		initTabConfig:function(){
			
		}
	});
	

	Ext.application({
	    name: 'MyApp',
	    mainView:'Ext.ux.TreeTab',
	    launch: function () {
	    }
	});
})(Ext,metaData);
